import { ResidentialZone } from './buildings/zones/ResidentialZone';
import { CommercialZone } from './buildings/zones/CommercialZone';
import { IndustrialZone } from './buildings/zones/IndustrialZone.js';
import { generateUUID } from 'three/src/math/MathUtils.js';
import config from '../config.js';
import { City } from './City.js';


type WorkSpaceType = CommercialZone | IndustrialZone;

/** 居民 */
export class Citizen {

    private static state = {
        idle: "idle",
        school: "school",
        employed: "employed",
        unemployed: "unemployed",
        retired: "retired"
    };

    id: string;
    name: string;
    age: number;
    state: string;
    stateCounter: number;
    residence: ResidentialZone;
    workplace: WorkSpaceType;

    constructor(residence: ResidentialZone) {

        this.id = generateUUID();


        this.name = generateRandomName();


        this.age = 1 + Math.floor(100 * Math.random());

        this.state = Citizen.state.idle;


        this.stateCounter = 0;


        this.residence = residence;

        this.workplace = null;

        this.initializeState();
    }

    /** 初始化居民状态，默认为学校状态，退休状态和失业状态 */
    private initializeState() {
        if (this.age < config.citizen.minWorkingAge) {
            this.state = Citizen.state.school;
        } else if (this.age >= config.citizen.retirementAge) {
            this.state = Citizen.state.retired;
        } else {
            this.state = Citizen.state.unemployed;
        }
    }

    simulate(city: City) {
        switch (this.state) {
            case Citizen.state.idle:
            case Citizen.state.school:
            case Citizen.state.retired:
                // Action - None

                // Transitions - None

                break;
            case Citizen.state.unemployed:
                // Action - Look for a job
                this.workplace = (this.findJob(city) as CommercialZone);

                // Transitions
                if (this.workplace) {
                    this.state = Citizen.state.employed;
                }

                break;
            case Citizen.state.employed:
                // Actions - None

                // Transitions
                if (!this.workplace) {
                    this.state = Citizen.state.unemployed;
                }

                break;
            default:
                console.error(`Citizen ${this.id} is in an unknown state (${this.state})`);
        }
    }

    dispose() {
        // Remove resident from its  workplace
        const workerIndex = this.workplace?.job.workers.indexOf(this);

        if (workerIndex !== undefined && workerIndex > -1) {
            this.workplace.job.workers.splice(workerIndex);
        }
    }

    /**
     * Search for a job nearby
     */
    private findJob(city: City) {
        const tile = city.findTile(this.residence, (tile) => {
            // Search for an industrial or commercial building with at least one available job
            if (tile.building?.type === 'industrial' ||
                tile.building?.type === 'commercial') {
                if ((tile.building as CommercialZone).job.availableJobs > 0) {
                    return true;
                }
            }

            return false;
        }, config.citizen.maxJobSearchDistance);

        if (tile) {
            // Employ the citizen at the building
            (tile.building as CommercialZone).job.workers.push(this);
            return tile.building;
        } else {
            return null;
        }
    }

    setWorkplace(workplace: CommercialZone) {
        this.workplace = workplace;
    }

    toHTML() {
        return `
      <li class="info-citizen">
        <span class="info-citizen-name">${this.name}</span>
        <br>
        <span class="info-citizen-details">
          <span>
            <img class="info-citizen-icon" src="/icons/calendar.png">
            ${this.age} 
          </span>
          <span>
            <img class="info-citizen-icon" src="/icons/job.png">
            ${this.state}
          </span>
        </span>
      </li>
    `;
    }
}

function generateRandomName() {
    const firstNames = [
        '赵', '钱', '孙', '李', '周',
        '吴', '郑', '王', '杨', '徐',
        '艾', '陈', '刘', '邓', '潘',
        '吴', '钟', '熊', '马',
    ];

    const lastNames = [
        '海', '彤', '大牛', '骥轩', '宇轩',
        '俊', '玉华', '雨寒', '鸿敏', '宜零',
        '灵艳', '鸿伟', '靖敏', '波', '献科',
        '牛牛', '马马', '霸霸',
    ];

    const randomFirstName = firstNames[Math.floor(Math.random() * firstNames.length)];
    const randomLastName = lastNames[Math.floor(Math.random() * lastNames.length)];

    return randomFirstName + ' ' + randomLastName;
}